<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: IndexController.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

session_write_close();

class Zimm_IndexController extends Zend_Controller_Action
{
    /**
     * Reads, processes, writes and serves an image.
     *
     * @return void
     */
    public function renderAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        @list($imageId, $instructionId) = explode('.', $this->_request->getParam('i2iId'));
        do {
            if (!$imageId || !$instructionId) {
                $this->_response->setHttpResponseCode(404);
                break;
            }

            $imgm = new Zimm_Model_DbTable_Images();
            if (!$image = $imgm->fetchImage($imageId)) {
                $this->_response->setHttpResponseCode(404);
                break;
            }

            $im = new Zimm_Model_DbTable_Instructions();
            if (!$instruction = $im->fetchInstruction($instructionId)) {
                $this->_response->setHttpResponseCode(404);
                break;
            }

            if ($file = $instruction->process($image, $imageInfo)) {
                header('Content-Type: ' . $imageInfo['content-type']);
                header('Content-Length: ' . $imageInfo['content-length']);
                header('Last-Modified: ' . gmdate("D, d M Y H:i:s", $imageInfo['last-modified']) . " GMT");
                header('Expires: ' .  gmdate("D, d M Y H:i:s", strtotime('+1 month')) . " GMT");
                header('Cache-Control:', true);
                header('Pragma:', true);

                header('Etag: ' . $imageInfo['etag']);
                if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $imageInfo['etag']) {
                    $this->_response->setHttpResponseCode(304);
                } else {
                    $obstatus = ob_get_status(true);
                    foreach ($obstatus as $s) {
                        ob_end_flush();
                    }

                    readfile($file);
                }
            } else {
                $this->_response->setHttpResponseCode(404);
            }
        } while (0);
    }
}